App({
    onLaunch: function() {
        // this.getUserInfo();
        this.autoUpdate();
    },

    getUserInfo: function(e) {
        var t = this;
        t.globalData.userInfo ? "function" == typeof e && e(t.globalData.userInfo) : wx.login({
            success: function(o) {
                var n = o.code;
                wx.getUserInfo({
                    withCredentials: !0,
                    lang: "zh_CN",
                    success: function(o) {
                        // console.log(o);
                        o.userInfo.code = n, t.doLogin(n, o), t.globalData.userInfo = o.userInfo, "function" == typeof e && e(t.globalData.userInfo);

                        // console.log('已授权')
                    },
                    fail: function(res) {
                        // wx.showModal({
                        //     title: "温馨提示",
                        //     content: "请点击确定，跳转到会员中心点击授权登录",
                        //     showCancel: false,
                        //     success: function(o) {
                        //         wx.getSetting({
                        //             success: function(o) {
                        //               t.switchTab("../user/index");
                        //             }
                        //         })
                        //     }
                        // });

                        // console.log('未授权')
                        wx.redirectTo({
                          url: '../authorizedLogin/authorizedLogin',
                        })
                    }
                });
            }
        });
    },
    doLogin: function(e, t) {
        var o = this;
        e ? wx.request({
            url: o.apiUrl("user/login"),
            method: "POST",
            data: {
                userinfo: t,
                code: e,
                ru_id: o.globalData.ru_id,
            },
            success: function (_e) {
              try {
                wx.setStorage({
                  key: "token",
                  data: _e.data.token
                }), wx.setStorage({
                  key: "openid",
                  data: _e.data.openid
                });
                o.region();
              } catch (err) {
                console.log('捕获到错误，重新加载')
                e.data = 0;
                wx.setStorage({
                  key: "token",
                  data: _e.data.token
                }), wx.setStorage({
                  key: "openid",
                  data: _e.data.openid
                });
                console.log('重新加载成功')
              }
            }
        }) : console.log("获取用户登录态失败！" + res.errMsg);
    },
    globalData: {
        userInfo: null,
        _linkTo: null,
        ru_id:127,
        url:"https://www.vpwyu.com/"
    },
    apiUrl: function(e) {
      return "https://www.vpwyu.com/wei/public/api/wx/" + e;
    },
    shwomessage: function(e) {
        var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 1e3, o = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : "warn";
        wx.showToast({
            title: e,
            icon: o,
            duration: t
        });
    },
    redirectTo: function(e) {
        wx.navigateTo({
            url: e
        });
    },
    switchTab: function (e) {
      wx.switchTab({
        url: e
      });
    },
    payOrder: function(e, t, o, n) {
        var a = this;
        wx.request({
            url: a.apiUrl("payment/pay"),
            data: {
                id: e,
                open_id: t,
                code: "order.pay",
                ru_id: a.globalData.ru_id
            },
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": o,
            },
            method: "POST",
            success: function(t) {
                if (500 != t.data.status_code) {
                    var i = t.data.data.wxpay;
                    "" != i && wx.requestPayment({
                        timeStamp: i.timestamp,
                        nonceStr: i.nonce_str,
                        package: i.packages,
                        signType: "MD5",
                        paySign: i.sign,
                        success: function(t) {
                            "requestPayment:ok" == t.errMsg && wx.request({
                                url: a.apiUrl("payment/notify"),
                                data: {
                                    id: e,
                                    form_id: n
                                },
                                method: "post",
                                header: {
                                    "Content-Type": "application/json",
                                    "X-ECTouch-Authorization": o
                                },
                                success: function(t) {
                                  var _redirect = '';
                                  if (getCurrentPages()[getCurrentPages().length - 2].route == '/pages/group/goods') {
                                    _redirect = '/pages/group/order/index';
                                  }
                                  console.log(_redirect);
                                    0 == t.data.data.code ? (wx.showToast({
                                        title: "支付成功",
                                        duration: 2e3
                                    }), _redirect!='' && a.redirectTo(_redirect),"" == t.data.data.extension_code && a.redirectTo("../order/index?objectId=" + e), 
                                      "team_buy" == t.data.data.extension_code && a.redirectTo(/*"../group/wait?objectId=" + t.data.data.team_id + "&user_id=" + t.data.data.user_id*/"/pages/group/order/index"), 
                                    "bargain_buy" == t.data.data.extension_code && a.redirectTo("../bargain/order/index?objectId=" + e)) : wx.showToast({
                                        title: "付款失败",
                                        image: "../../images/failure.png",
                                        duration: 2e3
                                    });
                                }
                            });
                        },
                        fail: function(t) {
                            wx.showToast({
                                title: "支付失败",
                                image: "../../images/failure.png",
                                duration: 2e3
                            }), a.redirectTo("../order/index?objectId=" + e);
                        }
                    });
                } else wx.showToast({
                    title: "支付失败",
                    image: "../../images/failure.png",
                    duration: 2e3
                });
            }
        });
    },
    region: function() {
        var e = this, t = [], o = wx.getStorageSync("token");
        wx.request({
            url: e.apiUrl("region/list"),
            data: {
                id: 1
            },
            method: "post",
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": o
            },
            success: function(e) {
                for (var o = e.data.data, n = [], a = [], i = 0; i < o.length; i++) {
                    n = o[i].region_name;
                    var r = {
                        province_id: a = o[i].region_id,
                        city_id: 0,
                        county_id: 0,
                        region_name: n,
                        region_id: a
                    };
                    t.push(r);
                    for (var s, c = o[i].region, d = [], u = 0; u < c.length; u++) {
                        var g = {
                            province_id: a,
                            city_id: u + 1,
                            county_id: 0,
                            region_name: d = c[u].region_name,
                            region_id: s = c[u].region_id
                        };
                        t.push(g);
                        for (var l, f = [], p = c[u].region, h = 0; h < p.length; h++) {
                            var w = {
                                province_id: a,
                                city_id: u + 1,
                                county_id: h + 1,
                                region_name: f = p[h].region_name,
                                region_id: l = p[h].region_id
                            };
                            t.push(w);
                        }
                    }
                }
                wx.setStorageSync("region", t);
            }
        });
    },
    getTimeLeft(datetimeTo) {
        // 计算目标与现在时间差（毫秒）
        let time1 = new Date(datetimeTo).getTime()
        let time2 = new Date().getTime()
        let mss = datetimeTo - time2;
        let days = parseInt(mss / (1000 * 60 * 60 * 24))
        let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
        let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60))
        let seconds = parseInt((mss % (1000 * 60)) / 1000)
        let obj = {
          day: days < 10 ? "0" + days : days,
          hour: hours < 10 ? "0" + hours : hours,
          minute: minutes < 10 ? "0" + minutes : minutes,
          second: seconds < 10 ? "0" + seconds : seconds,
          mss: mss,
        }
        return obj
    },
    // 强制更新
    autoUpdate: function() {
        var self = this
        // 获取小程序更新机制兼容
        if (wx.canIUse('getUpdateManager')) {
          const updateManager = wx.getUpdateManager()
          //1. 检查小程序是否有新版本发布
          updateManager.onCheckForUpdate(function(res) {
            // 请求完新版本信息的回调
            if (res.hasUpdate) {
              //检测到新版本，需要更新，给出提示
              wx.showModal({
                title: '更新提示',
                content: '检测到新版本，是否下载新版本并重启小程序？',
                success: function(res) {
                  if (res.confirm) {
                    //2. 用户确定下载更新小程序，小程序下载及更新静默进行
                    self.downLoadAndUpdate(updateManager)
                  } else if (res.cancel) {
                    //用户点击取消按钮的处理，如果需要强制更新，则给出二次弹窗，如果不需要，则这里的代码都可以删掉了
                    wx.showModal({
                      title: '温馨提示~',
                      content: '本次版本更新涉及到新的功能添加，旧版本无法正常访问的哦~',
                      showCancel:false,//隐藏取消按钮
                      confirmText:"确定更新",//只保留确定更新按钮
                      success: function(res) {
                        if (res.confirm) {
                          //下载新版本，并重新应用
                          self.downLoadAndUpdate(updateManager)
                        }
                      }
                    })
                  }
                }
              })
            }
          })
        } else {
          // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
          wx.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
          })
        }
      },
    // 下载小程序新版本并重启应用
      downLoadAndUpdate: function (updateManager){
        var self=this
        wx.showLoading();
        //静默下载更新小程序新版本
        updateManager.onUpdateReady(function () {
          wx.hideLoading()
          //新的版本已经下载好，调用 applyUpdate 应用新版本并重启
          updateManager.applyUpdate()
        })
        updateManager.onUpdateFailed(function () {
          // 新的版本下载失败
          wx.showModal({
            title: '已经有新版本了哟~',
            content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
          })
        })
      }
});